<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
const route = useRouter();
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Files, Document, Delete, FolderAdd } from '@element-plus/icons-vue'	//导入Search图标
import { quadratPage, quadratDelete, quadratExport, quadratExportDelete, qExport } from '@/utils/api.js'
import close from '@/assets/icon/close.svg'
import openLayer from "@/components/common/openlayer.vue";
import yfMap from '@/assets/img/yfdw.png'

import moment from 'moment';
const $moment = moment;
const multipleSelection = ref([]);

const handleSelectionSelectAll = (val) => {
    let arr = []
    val.forEach(e => {
        arr.push(e.id)
    })
    multipleSelection.value = arr;
}

const handleSelectionSelect = (val) => {
    let arr = []
    val.forEach(e => {
        arr.push(e.id)
    })
    multipleSelection.value = arr;
}


// 分页 B
const eel = ref([]);
const isdwn = ref(false);
const isMap = ref(false);
const ols = ref(null);
const yftype = ref('');
const keywords = ref('');
const pageSize = ref(20);
const pageNum = ref(1);
const totalElements = ref(100);
const currentPage = ref(1);
const handleCurrentChange = (val) => {
    pageNum.value = val;
    getanimalsSurveypage();
};

const getquadratExport = async () => {
    let res = await quadratExport()
    if (res.code == '200') {
        eel.value = res.data.content;

    }
}

const resp = () => {
    pageNum.value = 1;
    currentPage.value = 1;
    getanimalsSurveypage();
}

// 分页 E
const godetails = (data) => {
    let hisanimal = {
        "pageNum": pageNum.value,
        "keywords": keywords.value,
        "currentPage": currentPage.value
    }
    window.sessionStorage.setItem('hisanimal', JSON.stringify(hisanimal));

    route.push({ path: '/history/quadratSurvey/quadratSurveyDateils', query: { id: data.id } });
};
const list = ref([]);

const downZip = (item) => {
    // 创建一个下载链接
    let downloadLink = document.createElement('a');
    downloadLink.href = '/api/admin/quadrat/export/download/' + item.id;
    // downloadLink.download = item.name; // 设置下载文件的名称

    // 将下载链接添加到页面中（这一步可以根据实际情况进行调整）
    document.body.appendChild(downloadLink);

    // 模拟点击下载链接
    downloadLink.click();
}

const delItem = (item) => {
    ElMessageBox.confirm(
        '确定要删除这条数据吗?',
        '消息提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            quadratDelete(item).then((res) => {
                if (res.code == '200') {
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    })
                    getanimalsSurveypage();
                } else {
                    ElMessage({
                        type: 'warning',
                        message: res.msg,
                    })
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}

const getanimalsSurveypage = async () => {
    let res = await quadratPage(`?page=${pageNum.value}&size=15&type=${yftype.value}&keywords=${keywords.value}`)
    if (res.code == '200') {
        list.value = res.data.content;
        totalElements.value = res.data.totalElements;
    } else {
        ElMessage({
            message: res.message,
            type: 'warning',
        })
        list.value = []
    }
};

const getqExport = async () => {
    let res = await qExport(`?type=${yftype.value}&keywords=${keywords.value}`)
    if (res.code == '200') {
        getquadratExport()
    } else {
        ElMessage({
            message: res.message,
            type: 'warning',
        })
        list.value = []
    }
};

const looklt = (item) => {
    isMap.value = true
    setTimeout(function () {
        ols.value.previewshape([{
            id: item.id,
            name: item.yfName,
            borderColor: "",
            fillColor: "",
            iconSrc: yfMap,
            // data: {},
            geojson: { coordinates: [item.lon, item.lat], type: "Point" }
        }], 'ddddyfdd01s');
    }, 500)
}

const deldownZip = async (item) => {
    ElMessageBox.confirm(
        '确定要删除这条数据吗?',
        '消息提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            quadratExportDelete(item.id).then((res) => {
                if (res.code == '200') {
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    })
                    getquadratExport()
                } else {
                    ElMessage({
                        type: 'warning',
                        message: res.msg,
                    })
                }
            })

        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })


}


defineExpose({
    $moment
})

let usermsg = '';
onMounted(() => {
    usermsg = window.sessionStorage.getItem('usermsg');
    if (usermsg == undefined) {
        alert('您无权查看该网站，请登录后才能正常使用')
    } else {
        usermsg = JSON.parse(usermsg);
    };

    if (window.sessionStorage.getItem('hisanimal') != null) {
        let data = JSON.parse(window.sessionStorage.getItem('hisanimal'));
        pageSize.value = data.pageSize;
        pageNum.value = data.pageNum;
        keywords.value = data.keywords;
        currentPage.value = data.currentPage;
        getanimalsSurveypage();
        window.sessionStorage.removeItem('hisanimal')
    } else {
        getanimalsSurveypage();
    }

    // getquadratExport()
})
</script>
<template>
    <div>
        <div class="ha-title" style="margin-bottom: 16px;">
            <div>
                <span>样方调查</span>
            </div>
            <div style="display: flex;">
                <el-button :icon="FolderAdd" plain @click="getqExport">导出</el-button>
                <el-badge
                    style="margin:0 10px;display: flex;align-items: center;font-family: 'Microsoft YaHei', sans-serif;"
                    :value="eel.length" type="primary">
                    <el-button type="info" @click="getquadratExport(); isdwn = true" plain :icon="Files">
                        导出清单
                    </el-button></el-badge>
                <el-button :icon="Delete" @click="delItem(multipleSelection)" plain>删除({{ multipleSelection.length
                    }})</el-button>
            </div>
        </div>

        <el-row :gutter="10">
            <el-col :span="3">
                <el-select v-model="yftype" class="m-2" clearable placeholder="样方类型" size="large">
                    <el-option label="固定样方" value="固定样方" />
                    <el-option label="临时样方" value="临时样方" />
                </el-select>
            </el-col>

            <el-col :span="16"></el-col>
            <el-col :span="5">
                <el-input v-model="keywords" placeholder="搜索样方名称、样地编号" size="large" class="input-with-select">
                    <template #append>
                        <el-button :icon="Search" />
                    </template>
                </el-input>
            </el-col>
        </el-row>

        <el-table :data="list" style="width: 100%;margin-top: 16px;height: calc(100% - 140px);"
            @select-all="handleSelectionSelectAll" @select="handleSelectionSelect" :row-style="{ height: '50px' }"
            :header-cell-style="{ 'color': '#333', 'line-height': '40px' }">
            <el-table-column type="selection" width="35" />
            <el-table-column label="样方名称" prop="yfName" />
            <el-table-column label="样方编号" prop="yfNum" />
            <el-table-column label="调查时间">
                <template #default="scope">
                    <span>{{ $moment(scope.row.insertTime).format('YYYY-MM-DD') }}</span>
                </template>
            </el-table-column>


            <el-table-column label="操作" fixed="right" width="240">
                <template #default="scope">
                    <el-button type="info" @click.stop="godetails(scope.row)" :icon="Document" plain size="small">
                        详情
                    </el-button>
                    <el-button type="info" :icon="Document" @click.stop="looklt(scope.row)" plain size="small">
                        定位
                    </el-button>
                    <el-button type="info" plain :icon="Delete" @click.stop="delItem([scope.row.id])" size="small">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 B-->
        <div class="ml-page">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" background
                layout="total, prev, pager, next, jumper" :total="totalElements"
                @current-change="handleCurrentChange" />
        </div>
        <!-- 分页 E-->

        <div class="ha-form" v-if="isMap">
            <div class="hf-box">
                <div class="hf-close" @click.stop="isMap = false">
                    <img :src="close" alt="">
                </div>
                <div class="qzTitle">
                    <div></div>
                    <span>定位</span>
                </div>
                <div style="height: 16px;"></div>
                <div style="width: 100%;height: calc(100% - 40px);">
                    <open-layer ref="ols"></open-layer>
                </div>

            </div>
        </div>



        <div class="comm-frm" v-if="isdwn">
            <div class="comm-label" style="width: 700px;">
                <div class="comm-close" @click.stop="isdwn = false">
                    <img :src="close" alt="">
                </div>
                <div class="qzTitle">
                    <div></div>
                    <span>导出清单</span>
                </div>
                <br>
                <el-table :data="eel" height="600" style="width: 100%;" :row-style="{ height: '50px' }"
                    :header-cell-style="{ 'color': '#333', 'line-height': '40px' }">

                    <el-table-column label="样方编号" prop="recordNumber" width="200" show-overflow-tooltip />

                    <el-table-column label="生成时间">
                        <template #default="scope">
                            <span>{{ $moment(scope.row.createTime).format('YYYY-MM-DD') }}</span>
                        </template>

                    </el-table-column>
                    <el-table-column label="状态" prop="state">

                        <template #default="scope">
                            <el-button v-if="scope.row.state == '生成中'"
                                style="background-color:rgba(255, 195, 0, 0.1);border:none; color: #FFC300;">
                                {{ scope.row.state }}
                            </el-button>
                            <el-button v-else
                                style="background-color:rgba(56, 123, 255, 0.1);color:var(--wls-color);border:none;">
                                {{ scope.row.state }}
                            </el-button>
                        </template>

                    </el-table-column>
                    <el-table-column label="操作" fixed="right">
                        <template #default="scope">
                            <el-button type="info" :disabled="scope.row.state == '生成中'" @click.stop="downZip(scope.row)"
                                :icon="Document" plain size="small">
                                下载
                            </el-button>
                            <el-button type="info" @click.stop="deldownZip(scope.row)" plain :icon="Delete"
                                size="small">
                                删除
                            </el-button>

                        </template>
                    </el-table-column>
                </el-table>

            </div>
        </div>


    </div>
</template>
<style scoped>
.ha-form {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 9;
    background-color: rgba(0, 0, 0, .5);
}

.hf-box {
    width: 1000px;
    height: 800px;
    position: relative;
    padding: 24px;
    border-radius: 4px;
    background: #FFF;
    cursor: pointer;
}

.hf-close {
    position: absolute;
    top: 0;
    right: 0;
    cursor: pointer;
}


.comm-frm {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 9;
    background-color: rgba(0, 0, 0, .5);
}

.comm-label {
    width: 500px;
    padding: 24px;
    border-radius: 4px;
    background-color: #fff;
    position: relative;
    overflow: hidden;
}

.comm-close {
    position: absolute;
    top: 0;
    right: 0;
    cursor: pointer;
}

.comm-chedel {
    width: 26px;
    height: 26px;
    position: absolute;
    top: 8px;
    left: 8px;
    z-index: 3;
}

.comm-wavs {
    width: 100%;
    border-radius: 8px;
    display: flex;
    align-items: center;
    background-color: rgba(56, 123, 255, 0.1);
}
</style>